<script setup lang="ts">

import F_money from "@/components/common/f_money.vue";
import {ref, watch} from "vue";
import {type orderCreateResponse, orderStatusApi, type orderType} from "@/api/order_api";
import {Message, Notification} from "@arco-design/web-vue";

interface Props {
  visible: boolean
  order: orderCreateResponse
}
const iframeSrc = ref("");
const props = defineProps<Props>()
const emits = defineEmits(["update:visible", "success", "fail"])
const timer = ref<number>()

function cancel() {
  clearInterval(timer.value)
  emits("update:visible", false)
}

watch(() => props.visible, (newVal) => {
  if (newVal) {
    // 打开模态框时设置 src
    iframeSrc.value = props.order.payUrl;
    // 只有在模态框打开时才开始轮询
    timer.value = setInterval(async () => {
      const res = await orderStatusApi(props.order.no)
      if (res.code) {
        Message.error(res.msg)
        return
      }
      if (res.data.payStatus === 2) {
        // 支付成功
        Message.success("支付成功")
        emits("success")
        emits("update:visible", false)
        clearInterval(timer.value)
      }
      if (res.data.payStatus === 3) {
        // 支付超时
        Notification.warning({
          title: "支付超时",
          content: "订单已支付超时",
          closable: true,
          duration: 5 * 60 * 1000, // 5分钟
        })
        emits("fail")
        emits("update:visible", false)
        clearInterval(timer.value)
        return
      }
    }, 1000)
  } else {
    // 当模态框关闭时清理轮询

    clearInterval(timer.value)
    // 关闭模态框时清除 src
    iframeSrc.value = "";
    timer.value = undefined // 确保 timer 被清理
  }
})


</script>

<template>
  <a-modal body-class="payModalBody" @cancel="cancel" :footer="false" :width="400" :visible="props.visible"
           title="支付">
    <div class="container">
      <div class="price">
        <f_money :money="props.order.price"></f_money>
      </div>
      <div class="iframe">
        <iframe :src="iframeSrc" frameborder="0" scrolling="no" width="300" height="300px"></iframe>
      </div>
      <div class="notice">（目前只支持支付宝沙盒）</div>
    </div>
  </a-modal>
</template>

<style lang="less">
.payModalBody {
  .container {
    display: flex;
    flex-direction: column;
    align-items: center;

    .price {
      font-size: 34px;
      color: #f9a20f;
    }


    .notice {
      color: var(--color-text-2);
      margin-top: 10px;
    }
  }
}
</style>